<script lang="ts" setup>
import { ref } from 'vue';
import { InboxOutlined } from '@ant-design/icons-vue';
import { message } from 'ant-design-vue';
import { useFallBack } from './useFallBack';
import { useFileListStore } from '@/store/modules/dcp/image_management/fileList';
import { useImgEventStore } from '@/store/modules/dcp/image_management/imgEvent';
// 表格
const fileListStore = useFileListStore();
const dataSource = ref<any[]>([]);
const visible = ref<boolean>(false);
const fileList = ref<any[]>([]);
const eventList = ref<any[]>([]);
function getVisible() {
  visible.value = !visible.value;
}
const columns: any = [
  {
    title: '文件名',
    dataIndex: 'name',
    align: 'center',
    width: '20%',
    key: 'name',
  },
  {
    title: '上传名称',
    dataIndex: 'uploadName',
    align: 'center',
    width: '20%',
    key: 'uploadName',
  },
  {
    title: '文件上传进度',
    dataIndex: 'employeeName',
    align: 'center',
    key: 'employeename',
  },
  {
    title: '状态',
    dataIndex: 'state',
    align: 'center',
    width: '15%',
    key: 'state',
  },
  {
    title: '操作',
    dataIndex: 'operation',
    key: 'lastColumn',
    width: '15%',
    align: 'center',
  },
];
const confirmLoading = ref<boolean>(false);
async function handleOk() {
  confirmLoading.value = true;
  await customRequest();
  getVisible();
  confirmLoading.value = false;
}
// 获取文件夹
async function getEvent() {
  await useImgEventStore().getEventList();
  eventList.value = useImgEventStore().getList();
}
// 新增图片
const dateFormat = 'YYYY-MM-DD';
function formatDate(isoDateString: any) {
  if (!isoDateString || isoDateString === '') {
    return '';
  }
  const date = new Date(isoDateString);
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  return `${year}-${month}-${day} 00:00:00`;
}
const formRef = ref<any>([]);
const form = ref({
  department: '',
  main_personnel: '',
  event_name: '',
  event_time: '',
  event_location: '',
  tags: [],
  event_type: '',
  event: '',
});
const rules: any = {
  department: [{ required: true, message: '请输入事件发生的部门', trigger: 'blur' }],
  main_personnel: [{ required: true, message: '请输入主要人物', trigger: 'blur' }],
  event_name: [{ required: true, message: '请输入事件名称', trigger: 'blur' }],
  event_time: [{ required: true, message: '请输入事件发生的时间', trigger: 'blur' }],
};

// 获取标签
const options = ref<any[]>([]);
async function getTags() {
  await getImgInfoToUser().then((res: any) => {
    for (let i = 0; i < res.data.length; i++) {
      if (res.data[i].isAdmin === true) {
        const tags = res.data[i].tags.split(',');
        for (let i = 0; i < tags.length; i++) {
          options.value.push({ value: tags[i] });
        }
        break;
      }
    }
  });
}

onMounted(() => {
  getTags();
  getEvent();
  dataSource.value = fileListStore.getFileList();
});

function close() {
  fileList.value = [];
  getVisible();
}

// 重新上传
async function reUpload(fileItem: any) {
  await insertPicture(fileItem.imgData).then(() => {
    handleRemove(fileItem.file);
    fileItem.percent = '100';
    message.success('上传成功');
    fileItem.isUpload = true;
  }).catch((error) => {
    console.error(error);
    fileItem.percent = '0';
    message.error('上传失败');
    dataSource.value.splice(dataSource.value.findIndex(item => item.uid === fileItem.file.uid), 1);
    fileItem.isUpload = false;
  });
}
// 上传
function beforeUpload(file: any) {
  fileList.value = [];
  fileList.value.push(file);
  getVisible();
  return false; // 阻止自动上传
  // 在这里可以进行文件类型检查等
  // const isJPGOrPNG = file.type === 'image/jpeg' || file.type === 'image/png';
  // if (!isJPGOrPNG) {
  //   message.error('只能上传 JPG/PNG 文件!');
  // }
}

function handleRemove(file: any) {
  const index = fileList.value.findIndex((f: { uid: any }) => f.uid === file.uid);
  fileList.value.splice(index, 1);
}

// 自定义上传方法，可以根据实际情况进行替换
async function customRequest() {
  formRef.value = [];
  if (fileList.value.length === 0) {
    message.error('请上传文件！');
    return;
  }
  fileList.value.forEach(async (file: any) => {
    const formData = new FormData();
    formData.append('file', file);
    // 上传文件获取link
    const key = ref<string>('');
    await uploadFiles(formData).then((res: any) => {
      key.value = res.data.key;
    });
    let url = '';
    await getFilesUrl(key.value).then((res: any) => {
      url = res.data;
    });
    // 将数据存到数据库中
    const imgData = {
      department: form.value.department,
      mainPersonnel: form.value.main_personnel,
      eventName: form.value.event_name,
      eventTime: formatDate(form.value.event_time),
      eventLocation: form.value.event_location,
      tags: form.value.tags.join(','),
      eventType: form.value.event_type,
      downloadCount: 0,
      link: url,
      event: form.value.event,
    };
    // 存储到表格中
    fileListStore.addFile({ uid: file.uid, name: file.name, uploadName: form.value.event_name, percent: '0', imgData, file, isUpload: false });
    dataSource.value = fileListStore.getFileList();
    const item = dataSource.value.find(item => item.uid === file.uid);
    await insertPicture(imgData).then(() => {
      handleRemove(file);
      item.percent = '100';
      item.isUpload = true;
      message.success('上传成功!');
    }).catch(() => {
      message.error('上传失败!');
      item.percent = '0';
      item.isUpload = false;
    });
  });
}

// 预览
const visibleImg = ref<boolean>(false);
const imgItem = ref<any>();
function showModalImg(record: any) {
  imgItem.value = record;
  visibleImg.value = true;
}
// 判断是否为视频
function isMp4(link: any) {
  return link.toLowerCase().endsWith('.mp4');
}
</script>

<template>
  <PubPageMain class="max">
    <div class="header">
      <div class="left">
        <a-space>
          <div class="pjTitle">
            办公室图片管理
          </div>
        </a-space>
      </div>
    </div>
    <div class="content">
      <a-upload-dragger
        name="file" :before-upload="beforeUpload" :file-list="[]" :multiple="false" :drag="true"
        :on-remove="handleRemove"
      >
        <p class="ant-upload-drag-icon">
          <InboxOutlined />
        </p>
        <p class="ant-upload-text">
          拖拽文件到这里或者点击上传
        </p>
        <p class="ant-upload-hint">
          支持单次上传
        </p>
      </a-upload-dragger>
      <a-modal v-model:visible="visible" title="保存图片/视频的属性" :confirm-loading="confirmLoading" :closable="false">
        <a-form ref="formRef" :model="form" layout="vertical" :rules="rules">
          <a-row :gutter="16">
            <a-col :span="24">
              <a-form-item label="名称" name="event_name" prop="event_name">
                <a-input v-model:value="form.event_name" placeholder="请输入名称" />
              </a-form-item>
            </a-col>
          </a-row>
          <!-- <a-row :gutter="16">
            <a-col :span="24">
              <a-form-item label="主要人物" name="main_personnel" prop="main_personnel">
                <a-input v-model:value="form.main_personnel" placeholder="请输入主要人物" />
              </a-form-item>
            </a-col>
            <a-col :span="24">
              <a-form-item label="发生的部门" name="department" prop="department">
                <a-input v-model:value="form.department" placeholder="请输入发生的部门" />
              </a-form-item>
            </a-col>
          </a-row> -->
          <a-row :gutter="16">
            <a-col :span="12">
              <a-form-item label="发生的时间" name="event_time" prop="event_time">
                <a-date-picker v-model:value="form.event_time" style="width: 100%;" :format="dateFormat" />
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="发生的地点" name="event_location" prop="event_location">
                <a-input v-model:value="form.event_location" placeholder="请输入发生的地点" />
              </a-form-item>
            </a-col>
          </a-row>
          <a-row :gutter="16">
            <a-col :span="12">
              <a-form-item label="标签" name="tags" prop="tags">
                <a-select v-model:value="form.tags" :options="options" mode="multiple" placeholder="请选择标签" />
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="文件夹" name="event" prop="event">
                <a-select v-model:value="form.event" placeholder="请选择文件夹">
                  <a-select-option v-for="item in eventList" :key="item" :value="item">
                    {{ item }}
                  </a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
          </a-row>
          <a-row :gutter="16">
            <a-col :span="12">
              <a-form-item label="类型" name="event_type" prop="event_type">
                <a-input v-model:value="form.event_type" placeholder="请输入类型" />
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="主要人物" name="main_personnel" prop="main_personnel">
                <a-input v-model:value="form.main_personnel" placeholder="请输入主要人物" />
              </a-form-item>
            </a-col>
          </a-row>
          <a-row :gutter="16">
            <a-col :span="24">
              <a-form-item label="发生的部门" name="department" prop="department">
                <a-input v-model:value="form.department" placeholder="请输入发生的部门" />
              </a-form-item>
            </a-col>
          </a-row>
        </a-form>
        <template #footer>
          <a-button key="cancel" @click="close">
            取消
          </a-button>
          <a-button key="ok" type="primary" @click="handleOk">
            确定
          </a-button>
        </template>
      </a-modal>
      <a-table :columns="columns" :data-source="dataSource" row-key="uid">
        <template #bodyCell="{ column, record }">
          <template v-if="column.dataIndex === 'employeeName'">
            <a-progress :text-inside="true" :stroke-width="26" :percent="record.percent" />
          </template>
          <template v-else-if="column.dataIndex === 'state'">
            <div class="editable-row-operations">
              <span>
                <a-space>
                  <span v-if="record.isUpload" style="color: #52c41a;cursor: default;">上传成功</span>
                  <span v-if="!record.isUpload" style="color: red;cursor: default;">上传失败</span>
                </a-space>
              </span>
            </div>
          </template>
          <template v-else-if="column.dataIndex === 'operation'">
            <div class="editable-row-operations">
              <span>
                <a-space>
                  <a v-if="!record.isUpload" @click="reUpload(record)">重新上传</a>
                  <a @click="showModalImg(record)">预览</a>
                </a-space>
              </span>
            </div>
          </template>
        </template>
      </a-table>
    </div>
    <a-modal v-model:visible="visibleImg" footer="">
      <div v-if="isMp4(imgItem.imgData.link)">
        <video :src="imgItem.imgData.link" style="width: 100%;height: 18vw;" controls />
      </div>
      <a-image
        v-else :src="imgItem.imgData.link" :alt="imgItem.imgData.title" style="width: 100%;height: 18vw;"
        loading="lazy" :fallback="useFallBack().fallback"
      />
    </a-modal>
  </PubPageMain>
</template>

<style lang="scss" scoped>
.max {
  display: flex;
  flex-direction: column;
  max-width: 100%;
  max-height: 95%;
  overflow: auto;

  .header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    width: 100%;
    height: 3vw;
    margin-bottom: 0.5vw;

    .pjTitle {
      padding-left: 1vw;
      background: url("@/assets/images/title-left-bg.svg") no-repeat;
    }

    .right {
      display: flex;
      align-items: center;
    }
  }

  .content {
    box-sizing: border-box;
    display: flex;
    flex: 1;
    flex-direction: column;
    width: 100%;
    height: 95%;
    overflow: auto;
    overflow-y: auto;
  }
}
</style>
